package o2o.utils;

import com.jinyou.utils.common.DateUtils;
import com.jinyou.utils.common.ToolUtils;
import o2o.dao.VO.common.FileStoryInfo;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;

/**
 * Created by lmy on 2019/6/12 0012.
 */
public class FileUtils {
    // 保存视频
    public static FileStoryInfo saveVideo2Local(MultipartFile avator, String pathSetting, String urlSetting, String objfileName) throws Exception {
        return saveVideo2Local(avator, pathSetting, urlSetting, objfileName, false);
    }

    public static FileStoryInfo saveVideo2Local(MultipartFile avator, String pathSetting, String urlSetting, String objfileName, Boolean isCreateDateFile) throws Exception {
        if (avator.getSize() < 20 * 1024) {
            throw new Exception("文件过小，请上传大于20KB的文件");
        }
        if (pathSetting == null || urlSetting == null) {
            throw new Exception("网络连接错误，请联系管理员（10037）");
        }
        String fileName = null;
        String date = isCreateDateFile == null || isCreateDateFile == false ? DateUtils.sdfTime.get().format(new Date()) : "";
        String fname = ToolUtils.getNeedString(18);
        fileName = new StringBuilder(date).append("/").append(fname).toString();

        String imagePath = new StringBuilder(pathSetting).append("/").append(objfileName).append("/").toString();                     // 存储文件夹  分日期存储
        File file = new File(imagePath + date);
        if (!file.exists()) {
            file.mkdirs();
        }
        String type = avator.getOriginalFilename().substring(avator.getOriginalFilename().lastIndexOf("."));        // 类型
        File imgFile = new File(imagePath + fileName + type);
        try {
            avator.transferTo(imgFile);
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("保存文件错误，请重试！");
        }

        FileStoryInfo fileStoryInfo = new FileStoryInfo();
        fileStoryInfo.setName(fname + type);
        fileStoryInfo.setUrl(urlSetting + "/" + objfileName + "/" + fileName + type);
        fileStoryInfo.setReativeAddr(objfileName + "/" + fileName + type);                // 相对位置
        fileStoryInfo.setStoryAddr(imagePath + fileName + type);

        return fileStoryInfo;
    }

    public static void forceMkdirParent(File file) throws IOException {
        File parent = file.getParentFile();
        if (parent != null) {
            org.apache.commons.io.FileUtils.forceMkdir(parent);
        }
    }
}
